package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {
    private static final Logger log = LoggerFactory.getLogger(ClazzServiceImpl.class);
    @Autowired
    private ClazzMapper clazzMapper;

    /**
     * 查询所有班级信息
     *
     * @return
     */
    @Override
    public List<Clazz> findAll() {
        return clazzMapper.select();
    }

    /**
     * 条件分页查询
     *
     * @return
     */
    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        log.info("请求参数：{}", clazzQueryParam);
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        Page<Clazz> list = clazzMapper.selectPage(clazzQueryParam);
        log.info("查询结果：{}", list);
        list.forEach(clazz -> {
            if (LocalDate.now().isBefore(clazz.getBeginDate())) {
                clazz.setStatus("未开课");
            } else if (LocalDate.now().isAfter(clazz.getEndDate())) {
                clazz.setStatus("已结课");
            } else clazz.setStatus("在读");
        });
        return new PageResult<>(list.getTotal(), list.getResult());
    }

    /**
     * 根据id查询班级信息
     *
     * @param id
     * @return
     */
    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.selectById(id);
    }

    /**
     * 更新班级信息
     *
     * @param clazz
     */
    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }

    /**
     * 添加班级信息
     *
     * @param clazz
     * @return
     */
    @Override
    public int save(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(clazz.getCreateTime());
        return clazzMapper.insert(clazz);
    }

    /**
     * 删除班级信息
     */
    @Override
    public void delete(Integer id) {
        clazzMapper.deleteById(id);
    }
}
